package day31;

import java.io.*;
import java.net.*;

/**
 * 简化版客户端程序
 * 实现基本的Socket客户端功能，连接到服务器并进行通信
 */
public class Client {
    // 服务器地址和端口
    private static final String SERVER_ADDRESS = "localhost";
    private static final int SERVER_PORT = 8888;
    
    public static void main(String[] args) {
        System.out.println("客户端启动中...");
        
        // 建立到服务器的连接
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        BufferedReader stdIn = null;
        
        try {
            socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            stdIn = new BufferedReader(new InputStreamReader(System.in));
            
            System.out.println("已连接到服务器");
            
            // 读取服务器发送的欢迎消息
            String serverResponse = in.readLine();
            System.out.println("服务器: " + serverResponse);
            
            System.out.println("请输入消息 (输入'bye'退出):");
            
            String userInput;
            // 循环读取用户输入并发送到服务器
            while ((userInput = stdIn.readLine()) != null) {
                // 发送消息到服务器
                out.println(userInput);
                
                // 接收服务器响应
                serverResponse = in.readLine();
                System.out.println("服务器: " + serverResponse);
                
                // 如果用户输入"bye"则退出循环
                if ("bye".equals(userInput)) {
                    break;
                }
            }
        } catch (Exception e) {
            // 简单处理异常，但不显示详细错误信息
            System.out.println("发生错误");
        } finally {
            // 关闭所有资源
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (stdIn != null) stdIn.close();
                if (socket != null) socket.close();
            } catch (Exception e) {
                // 忽略关闭时的异常
            }
        }
        
        System.out.println("客户端已关闭");
    }
}